//
//  CompanyMembersListVC.m
//  NtoccShipper
//
//  Created by mac on 2020/1/9.
//  Copyright © 2020 zhuchongjin. All rights reserved.
//

#import "CompanyMembersListVC.h"
#import "CompanyMembersCell.h"
#import "CompanyMembersModel.h"
#import "AddCompanyMembersVC.h"
#import "AllocatedBalanceView.h"

@interface CompanyMembersListVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) CompanyMembersCell *companyMembersCell;
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (copy, nonatomic) NSString *strStatus; // 货源状态
@property (nonatomic, strong) AllocatedBalanceView *allocatedView;
@end

@implementation CompanyMembersListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor cjBackgroundColor];
//    DLog(@"self.indexPage======%@",self.indexPage);
    self.companyMembersCell = [[CompanyMembersCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self.view addSubview:self.tableView];
    
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
    
    CJRegisterNotify(CJCompanyMembersRefresh, @selector(getRefreshData:));
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.tableView.mj_header beginRefreshing];
}

-(void)getRefreshData:(NSNotification *)notification{
//    DLog(@"=====%@",notification.object);
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ws.tableView.mj_header beginRefreshing];
    });
}

- (void)dealloc{
    CJRemoveNofify;
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {
    
    
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/shipment/shipmentEmployees",CJBaseUrl);
    NSDictionary *dic = @{
        @"pageNum":CJStringWithFormat(@"%d",self.page),
        @"pageSize":@"10",
        @"roleCode":self.strRoleCode
    };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:GetType url:strUrl parameters:dic status:ArpaDefault success:^(id  _Nonnull responseObject) {
        
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
        
        if (total.intValue == 0 && self.page == 1) {
             [ws.modelArray removeAllObjects];
        }

        if ([ws.refreshType isEqualToString:@"down"]) {
            [ws.modelArray removeAllObjects];
        }
        NSError *error;
        NSArray *arr = [CompanyMembersModel arrayOfModelsFromDictionaries:list error:&error];
        [ws.modelArray addObjectsFromArray:arr];

        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];

        if (ws.modelArray.count == total.intValue) {
            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
        }

  
        [ws.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
    
//    此处为老的数据 暂时保留  需要删除
//   [@"发货人",@"财务",@"收货人",@"上游客户" ,@"代付机构"];
//    if (self.indexPage.intValue == 0) {
//        self.strStatus = @"2";
//
//    }else if (self.indexPage.intValue == 1){
//
//        self.strStatus = @"3";
//
//    }else if (self.indexPage.intValue == 2){
//
//        self.strStatus = @"4";
//
//    }else if (self.indexPage.intValue == 3){
//
//        self.strStatus = @"5";
//
//    }else if (self.indexPage.intValue == 4){
//
//        self.strStatus = @"6";
//
//    }
//
//    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/shipment",CJBaseUrl);
//    NSDictionary *dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
//                             @"pageSize":@"10",
//                             @"staffType":self.strStatus,
//                            };
//    WS(ws);
//    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
//
//        DLog(@"++++++++%@",responseObject);
//        NSArray *list = responseObject[@"records"];
//        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
//        if (total.intValue == 0 && self.page == 1) {
//             [ws.modelArray removeAllObjects];
//        }
//        if (list.count > 0) {
//
//            if ([ws.refreshType isEqualToString:@"down"]) {
//                [ws.modelArray removeAllObjects];
//            }
//            NSError *error;
//            NSArray *arr = [CompanyMembersModel arrayOfModelsFromDictionaries:list error:&error];
//            [ws.modelArray addObjectsFromArray:arr];
//
//            [ws.tableView.mj_header endRefreshing];
//            [ws.tableView.mj_footer endRefreshing];
//
//            if (ws.modelArray.count == total.intValue) {
//                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//            }
//
//        }else{
//
//            [ws.tableView.mj_header endRefreshing];
//            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
//
//        [ws.tableView reloadData];
//    } failure:^(NSError * _Nonnull error) {
//        DLog(@"++++++++%@",error);
//        [ws.tableView.mj_header endRefreshing];
//        [ws.tableView.mj_footer endRefreshing];
//    }];

}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"CompanyMembersCell";
    CompanyMembersCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[CompanyMembersCell alloc] initWithFlex:nil reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    CompanyMembersModel *model = self.modelArray[indexPath.row];
    [cell setCellInfoWithModel:model];
    
    WS(ws);
    cell.blockPhone = ^(id anyObject) {
        [CJControl clickPhoneWithPhoneNum:model.phone];
    };
    cell.blockDelete = ^(id anyObject) {
        [ws delectAppectGroupAction:model];
    };
    cell.blockEditor = ^(id anyObject) {
        [ws changeAppectGroupAction:model];
    };
    cell.blockFenP = ^(id anyObject) {
        self.allocatedView = [[AllocatedBalanceView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) code:model.partyCode];
        [self.allocatedView.cententButton addTarget:self action:@selector(cententAction) forControlEvents:(UIControlEventTouchUpInside)];
        self.allocatedView.blockText = ^(id anyObject) {
            NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/shipment/virtualAmountApp/%@",CJBaseUrl,model.partyCode);
            NSDictionary *dicPar = @{@"virtualAmount":ws.allocatedView.textField.text};

            [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
                [CJAlert showStringDismissWithDelay:@"分配成功"];
                [ws.allocatedView removeFromSuperview];
            } failure:^(NSError * _Nonnull error) {
                    
            }];

           
        };
        [[UIApplication sharedApplication].keyWindow addSubview:self.allocatedView];
    };
    return cell;
}
- (void)cententAction{
    [self.allocatedView removeFromSuperview];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

- (void)delectAppectGroupAction:(CompanyMembersModel *)model{
    
    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"删除提示" strContent:CJStringWithFormat(@"确定要删除%@吗？",model.userName) ClickOnSure:^(NSString * _Nonnull strSure) {
      
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/shipment",CJBaseUrl);
        NSDictionary *dicPar = @{@"codes":model.code
        };
        WS(ws);
        [[HDNetworking sharedHDNetworking] DELETE:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
            
            DLog(@"++++++++%@",responseObject);
            [ws.tableView.mj_header beginRefreshing];

        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
            
        }];

    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
        DLog(@"-=-=-=-=");
    }];
    
    alert.center = KEYWINDOW.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss=YES;
    [alertView show];
}

- (void)changeAppectGroupAction:(CompanyMembersModel *)model{
    AddCompanyMembersVC *vc = [AddCompanyMembersVC new];
    vc.isChange = YES;
    vc.model = model;
    vc.strRole = self.strRole;
//    vc.strRoleCode = self.strRoleCode;
    vc.strRoleName = self.strRoleName;
    WS(ws);
    vc.blockChange = ^(id anyObject) {
        [ws.tableView.mj_header beginRefreshing];
    };
    [self pushVc:vc];
}


- (void)pushVc:(UIViewController *)vc {
    
    if ([vc isKindOfClass:[UIViewController class]] == NO) return ;
    if (self.navigationController == nil) return ;
    if (vc.hidesBottomBarWhenPushed == NO) {
        vc.hidesBottomBarWhenPushed = YES;
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight , SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - kNavBarHeight -CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}

@end
